package com.sinosoft.cloud.access.transformer.function;

import com.sinosoft.lis.pubfun.PubFun;
import io.netty.util.internal.StringUtil;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by zg on 2016/8/12.
 * 用于XSL转换非标准报文到标准报文时的填充内容。传入相关节点内容作为参数，返回核心需要的标准报文的填充节点值
 */
public class XSLTransfromFunction {

    private static List<String[]> ldcoms;

//    public static RedisCommonDao mRedisCommonDao = SpringContextUtils.getBeanByClass(RedisCommonDao.class);


    //获取保单核保时的投保人的婚姻状况
    public static String getMarriage(String saleChnl) {
        String marriage = "";

        return marriage;
    }

    //获取yyyyMMdd格式的日期 ，如20160805
    public static String getFormatDate(String cTranDate) {
        String tranDate = "";
        if (cTranDate != null && !"".equals(cTranDate)) {
            tranDate = cTranDate.replaceAll("-", "").replaceAll("/", "").trim();
        }
        return tranDate;
    }

    //获取时间格式为hhmmss ，如152030
    public static String getFormatTime(String cTranTime) {
        String tranTime = "";
        if (cTranTime != null && !"".equals(cTranTime)) {
            tranTime = cTranTime.replaceAll(":", "").trim();
        }
        return tranTime;
    }

    /**
     * 获取日期时间类型字段，格式为yyyyMMdd hhmmss 如 20161012 152030
     *
     * @param cTranDate 2016-10-12 或 20161012
     * @param cTranTime 15:20:30 或 152030
     * @return 格式为yyyyMMdd hhmmss
     */
    public static String getFormatDateTime(String cTranDate, String cTranTime) {
        String tranDateTime = "";
        String tranDate = "";
        String tranTime = "";
        if (cTranDate != null && !"".equals(cTranDate)) {
            tranDate = cTranDate.replaceAll("-", "").replaceAll("/", "").trim();
        }
        if (cTranTime != null && !"".equals(cTranTime)) {
            tranTime = cTranTime.replaceAll(":", "").trim();
        }
        tranDateTime = tranDate + " " + tranTime;
        return tranDateTime;
    }

    /**
     * 获取日期时间类型字段，格式为yyyy-MM-dd HH:mm:ss 如 2016-10-12 15:20:30
     *
     * @param cTranDate 2016-10-12 或 20161012
     * @param cTranTime 15:20:30 或 152030
     * @return 格式为yyyy-MM-dd HH:mm:ss
     */
    public static String getFormatDateTime2(String cTranDate, String cTranTime) {
        String tranDateTime = "";
        String tranDate = "";
        String tranTime = "";
        String tempTranDate = "";
        String tempTranTime = "";

        if (cTranDate != null && !"".equals(cTranDate.trim()) && cTranDate.trim().length() <= 10) {
            tempTranDate = cTranDate.replace("-", "").replace("/", "").trim();
            tranDate = tempTranDate.substring(0, 4) + "-" + tempTranDate.substring(4, 6) + "-" + tempTranDate.substring(6, 8);
        } else {
            tranDate = cTranDate;
        }
        if (cTranTime != null && !"".equals(cTranTime.trim()) && cTranTime.trim().length() <= 8) {
            tempTranTime = cTranTime.replace(":", "").trim();
            tranTime = tempTranTime.substring(0, 2) + ":" + tempTranTime.substring(2, 4) + ":" + tempTranTime.substring(4, 6);
        } else {
            tranTime = cTranTime;
        }
        tranDateTime = tranDate + " " + tranTime;
        return tranDateTime;
    }

    /**
     * 传入的日期和时间格式为yyyy-MM-dd HH:mm:ss 或 yyyyMMdd HH:mm:ss 或 yyyy/MM/dd HH:mm:ss 或 yyyy-MM-dd HHmmss 或 yyyyMMdd HHmmss 或 yyyy/MM/dd HHmmss
     * 返回yyyyMMdd格式的日期 ，如：传入 2016-10-11 13:13:13 则返回 20161011
     *
     * @param cTranDateTime
     * @return yyyyMMdd格式的日期
     */
    public static String getFormatDateFromDateTime(String cTranDateTime) {
        String tranDate = "";
        if (cTranDateTime != null && !"".equals(cTranDateTime.trim())) {
            tranDate = cTranDateTime.trim().replace("-", "").replace("/", "").replace(":", "").substring(0, 8).trim();
        }
        return tranDate;
    }

    /**
     * 传入的日期和时间格式为yyyy-MM-dd HH:mm:ss 或 yyyyMMdd HH:mm:ss 或 yyyy/MM/dd HH:mm:ss 或 yyyy-MM-dd HHmmss 或 yyyyMMdd HHmmss 或 yyyy/MM/dd HHmmss
     * 返回时间格式为hhmmss ，如传入 2016-10-11 13:13:13 则返回 131313
     *
     * @param cTranDateTime
     * @return 时间格式为hhmmss的时间
     */
    public static String getFormatTimeFromDateTime(String cTranDateTime) {
        String tranTime = "";
        if (cTranDateTime != null && !"".equals(cTranDateTime.trim())) {
            String temp = cTranDateTime.trim().replace("-", "").replace("/", "").replace(":", "");
            tranTime = temp.substring(8, temp.length()).trim();
        }
        return tranTime;
    }

    /**
     * 功能描述：去除字符串首部为"0"字符
     *
     * @param str 传入需要转换的字符串
     * @return 转换后的字符串
     */
    public static String removeZero(String str) {
        char ch;
        String result = "";
        if (str != null && str.trim().length() > 0 && !str.trim().equalsIgnoreCase("null")) {
            try {
                for (int i = 0; i < str.length(); i++) {
                    ch = str.charAt(i);
                    if (ch != '0') {
                        result = str.substring(i);
                        break;
                    }
                }
            } catch (Exception e) {
                result = "";
            }
        } else {
            result = "";
        }
        return result;
    }

    /**
     * 获取以元为单位的金额 字符串类型
     *
     * @param fenMoney 传入以分为单位的金额
     * @return 转换后的金额字符串 以元为单位
     */
    public static String getYuanMoney(String fenMoney) {
        if (fenMoney == null)
            return "0.00";
        String s = fenMoney;
        int len = -1;
        StringBuilder sb = new StringBuilder();
        if (s != null && s.trim().length() > 0 && !s.equalsIgnoreCase("null")) {
            s = removeZero(s);
            if (s != null && s.trim().length() > 0 && !s.equalsIgnoreCase("null")) {
                len = s.length();
                int tmp = s.indexOf("-");
                if (tmp >= 0) {
                    if (len == 2) {
                        sb.append("-0.0").append(s.substring(1));
                    } else if (len == 3) {
                        sb.append("-0.").append(s.substring(1));
                    } else {
                        sb.append(s.substring(0, len - 2)).append(".").append(s.substring(len - 2));
                    }
                } else {
                    if (len == 1) {
                        sb.append("0.0").append(s);
                    } else if (len == 2) {
                        sb.append("0.").append(s);
                    } else {
                        sb.append(s.substring(0, len - 2)).append(".").append(s.substring(len - 2));
                    }
                }
            } else {
                sb.append("0.00");
            }
        } else {
            sb.append("0.00");
        }
        return sb.toString();
    }

    /**
     * 功能描述：金额字符串转换：单位元转成单位分
     *
     * @param yuanMoney 传入需要转换的金额字符串 单位元
     * @return 转换后的金额字符串 单位分
     */
    public static String getFenMoney(String yuanMoney) {
        if (yuanMoney == null)
            return "0";
        String s = yuanMoney;
        int posIndex = -1;
        String str = "";
        StringBuilder sb = new StringBuilder();
        if (s != null && s.trim().length() > 0 && !s.equalsIgnoreCase("null")) {
            posIndex = s.indexOf(".");
            if (posIndex > 0) {
                int len = s.length();
                if (len == posIndex + 1) {
                    str = s.substring(0, posIndex);
                    if (str == "0") {
                        str = "";
                    }
                    sb.append(str).append("00");
                } else if (len == posIndex + 2) {
                    str = s.substring(0, posIndex);
                    if (str == "0") {
                        str = "";
                    }
                    sb.append(str).append(s.substring(posIndex + 1, posIndex + 2)).append("0");
                } else if (len == posIndex + 3) {
                    str = s.substring(0, posIndex);
                    if (str == "0") {
                        str = "";
                    }
                    sb.append(str).append(s.substring(posIndex + 1, posIndex + 3));
                } else {
                    str = s.substring(0, posIndex);
                    if (str == "0") {
                        str = "";
                    }
                    sb.append(str).append(s.substring(posIndex + 1, posIndex + 3));
                }
            } else {
                sb.append(s).append("00");
            }
        } else {
            sb.append("0");
        }
        str = removeZero(sb.toString());
        if (str != null && str.trim().length() > 0 && !str.trim().equalsIgnoreCase("null")) {
            return str;
        } else {
            return "0";
        }
    }

    /**
     * 保险期限单位获取
     *
     * @param InsPeriod 带符号的保险期限
     * @return 最后一位保险期限单位若没有默认单位A(年龄)
     */
    public static String getInsuYearFlag(String InsPeriod) {
        if (InsPeriod != null && !"".equals(InsPeriod)) {
            return InsPeriod.substring(InsPeriod.length() - 1);
        }
        return "Y";
    }

    /**
     * 保险期限年期获取
     *
     * @param InsPeriod 带符号的保险期限
     * @return 去除保险期限最后一位的符号的保险年期
     */
    public static String getInsuYear(String InsPeriod) {
        if (InsPeriod != null && !"".equals(InsPeriod)) {
            return InsPeriod.substring(0, InsPeriod.length() - 1);
        }
        return "10";
    }

    /**
     * 受益人与被保人关系枚举值转换
     *
     * @param RelationToInsured 带符号的保险期限
     * @return 去除保险期限最后一位的符号的保险年期
     */
    public static String getRelationToInsured(String RelationToInsured) {
        if (RelationToInsured == null || "".equals(RelationToInsured)) return "";
        if ("01".equals(RelationToInsured) || "02".equals(RelationToInsured)) return "02";
        if ("03".equals(RelationToInsured) || "04".equals(RelationToInsured)) return "01";
        if ("05".equals(RelationToInsured) || "06".equals(RelationToInsured)) return "03";
        return RelationToInsured;
    }

    /**
     * 获取当前日期后一天
     *
     * @return
     */
    public static String getCurrDateAfterDay(String abFlag, String afterDay) {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        Date date = new Date();
        if ("A".equals(abFlag)) date.setTime(date.getTime() + (1000 * 60 * 60 * 24) * new Integer(afterDay));
        if ("B".equals(abFlag)) date.setTime(date.getTime() - (1000 * 60 * 60 * 24) * new Integer(afterDay));
        return format.format(date);
    }

    /**
     * 获取当前日期前五年
     *
     * @return
     */
    public static String getCurrDateBeforeyear(String abFlag, String beforeYear) {
        String currentDate = PubFun.getCurrentDate();
        String[] split = currentDate.split("-");
        Integer curryear = new Integer(split[0]);
        if ("A".equals(abFlag)) return (curryear + new Integer(beforeYear)) + split[1] + split[2];
        if ("B".equals(abFlag)) return (curryear - new Integer(beforeYear)) + split[1] + split[2];
        return "";
    }

    /**
     * 获取指定日期前后N天后的日期
     *
     * @param date     指定日期
     * @param abFlag   前后标记
     * @param afterDay 天数
     * @return
     */
    public static String getThisDateAfterDay(String date, String abFlag, String afterDay) {
        try {
            if (StringUtil.isNullOrEmpty(date)) return "";
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
            Date newdate = format.parse(date.replaceAll("-", "").replaceAll("/", ""));
            if ("A".equals(abFlag)) newdate.setTime(newdate.getTime() + (1000 * 60 * 60 * 24) * new Integer(afterDay));
            if ("B".equals(abFlag)) newdate.setTime(newdate.getTime() - (1000 * 60 * 60 * 24) * new Integer(afterDay));
            SimpleDateFormat tformat = new SimpleDateFormat("yyyy-MM-dd");
            return tformat.format(newdate);
        } catch (ParseException e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 通过告知类型,告知编码获取对应告知的详细内容
     *
     * @param ImpartVer
     * @param ImpartCode
     * @return
     */
    public static String getImpartContent(String ImpartVer, String ImpartCode) {

        if ("29".equals(ImpartVer) && "7a".equals(ImpartCode)) {
            return "被保险人是否曾被任何保险公司拒保、延期?";
        }
        if ("29".equals(ImpartVer) && "7b".equals(ImpartCode)) {
            return "被保险人是否目前患有或曾经患有下列疾病或症状? 先天性心脏病、心力衰竭；脑出血、脑栓塞、脑动静脉血管瘤及畸形；肝硬化、肝衰竭；尿毒症、肾衰竭；恶性肿瘤或脑部良性肿瘤；先天性疾病、遗传性疾病、职业病（如尘肺、矽肺）；是否有身体残障，酒精或药物滥用成瘾?";
        }
        if ("29".equals(ImpartVer) && "7c".equals(ImpartCode)) {
            return "您是否曾于过去三年内被要求接受手术、病理检查、放化疗?或因病计划在近期进行手术?";
        }
        if ("Agent".equals(ImpartVer) && "Name".equals(ImpartCode)) {
            return "网销业务员";
        }
        return "";
    }


    public static String getCodeName(String CodeType, String CodeValue) {
        if ("EdorReasonCode".equals(CodeType) && "02".equals(CodeValue)) {
            return "急需用钱";
        }
        return "";
    }


    public static String getCurrValueAddOne(String value) {
        try {
            return (new Integer(value) + 1) + "";
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return "";
        }
    }


    /**
     * 将金额从元转换为分，参数是string类型
     * @param pYuan
     * @return
     */
    public static long yuanToFen(String pYuan) {
        return pYuan != null && !"".equals(pYuan)?Math.round(Double.parseDouble(pYuan) * 100.0D):0L;
    }

    /**
     * 将金额从元转换为分，参数是double类型
     * @param pYuan
     * @return
     */
    public static long yuanToFen(double pYuan) {
        return Math.round(pYuan * 100.0D);
    }

    /**
     * 将金额从分转换为元，参数是string类型
     * @return
     */
    public static String fenToYuan(String pFen) {
        return pFen != null && !"".equals(pFen)?(new DecimalFormat("0.00")).format((double)Long.parseLong(pFen) / 100.0D):pFen;
    }

    /**
     * 将金额从分转换为元，参数是long类型
     * @return
     */
    public static String fenToYuan(long pFen) {
        return (new DecimalFormat("0.00")).format((double)pFen / 100.0D);
    }

    /**
     * 在返回结果后面加上N个空格。N代表第二个参数。
     * 两个参数的方法：第一个参数是字符串，第二个参数是多少个空格
     * @param pSrcStr
     * @param pLength
     * @return
     */
    public static String fillStrWith_2Args(String pSrcStr, int pLength) {
        return fillStrWith_(pSrcStr, pLength, false);
    }

    /**
     * 在返回结果后面加上N个空格,N代表第二个参数，第三个参数代表
     * 三个参数的方法
     * @param pSrcStr
     * @param pLength
     * @return
     */
    public static String fillStrWith_(String pSrcStr, int pLength, boolean pLeftAdd) {
        return fillStr(pSrcStr, pLength, ' ', pLeftAdd);
    }

    public static String fillStr(String pSrcStr, int pLength, char pFillChar, boolean pLeftAdd) {
        return fillStr(pSrcStr, pLength, pFillChar, pLeftAdd, "GBK");
    }

    public static String fillStr(String pSrcStr, int pLength, char pFillChar, boolean pLeftAdd, String pCharset) {
        if(pSrcStr == null) {
            return null;
        } else {
            int mSrcBytesLen = 0;

            try {
                mSrcBytesLen = pSrcStr.getBytes(pCharset).length;
            } catch (UnsupportedEncodingException var8) {
                var8.printStackTrace();
            }

            StringBuilder mStrBuilder = new StringBuilder();
            int i;
            if(pLeftAdd) {
                for(i = mSrcBytesLen; i < pLength; ++i) {
                    mStrBuilder.append(pFillChar);
                }

                mStrBuilder.append(pSrcStr);
            } else {
                mStrBuilder.append(pSrcStr);

                for(i = mSrcBytesLen; i < pLength; ++i) {
                    mStrBuilder.append(pFillChar);
                }
            }

            return mStrBuilder.toString();
        }
    }

    /**
     * 将八位日期字符串转换为十位日期字符串。例如yyyyMMdd转换为yyyy-MM-dd
     * @param pDate
     * @return
     */
    public static String date8to10(String pDate) {
        if(pDate != null && !"".equals(pDate)) {
            char[] mChars = pDate.toCharArray();
            return (new StringBuilder()).append(mChars, 0, 4).append('-').append(mChars, 4, 2).append('-').append(mChars, 6, 2).toString();
        } else {
            return pDate;
        }
    }

    /**
     * 将十位日期字符串转换为八位日期字符串。例如yyyy-MM-dd转换为yyyyMMdd
     * @param pDate
     * @return
     */
    public static String date10to8(String pDate) {
        return pDate != null && !"".equals(pDate)?pDate.substring(0, 4) + pDate.substring(5, 7) + pDate.substring(8):pDate;
    }

    /**
     * 将字符串转换为boolean
     * @param booleanStr
     * @return
     */
    public static Boolean parseBoolean(String booleanStr){
        return Boolean.parseBoolean(booleanStr);
    }

    /**
     * 投保人家庭年收入处理
     * @param Flag
     * @param appntIncome
     * @return
     */
    public static String appntIncomeFormat(String Flag,String appntIncome){
        if(!("").equals(Flag)&&(Flag!=null&&("01").equals(Flag)||Flag!=null&&("02").equals(Flag))){
            appntIncome=appntIncome.indexOf("-")>-1 ? appntIncome.substring(0,appntIncome.indexOf("-")):appntIncome;
            if(("5").equals(appntIncome)){//投保人年收入为5-10万
                return appntIncome;
            }else{
                String regEX="[^0-9]";
                Pattern p = Pattern.compile(regEX);
                Matcher m = p.matcher(appntIncome);
                appntIncome=m.replaceAll("");//将匹配到的matcher数字转化为String类型数字可用m.replaceAll("")
                if(!("").equals(appntIncome)&&appntIncome!=null&&Double.parseDouble(appntIncome)<=5){//投保人年收入为5万以下
                    appntIncome="0";
                }
            }
        }else if(!("").equals(Flag)&&Flag!=null&&("04").equals(Flag)){
            if(!("").equals(appntIncome)&&appntIncome!=null){
                double numberIncome=Double.parseDouble(appntIncome)/10000;
                appntIncome=Double.toString(numberIncome);
            }
        }else {
            if(!("").equals(appntIncome)&&appntIncome!=null){
                double numberIncome=Double.parseDouble(appntIncome)/10000;
                appntIncome=Double.toString(numberIncome);
            }
        }
        return appntIncome;
    }

    /**
     * 投保人家庭年收入处理
     * @param Flag
     * @param appntIncome
     * @return
     */
    public static String insuredIncomeFormat(String Flag,String appntIncome){
        if(!("").equals(Flag)&&(Flag!=null&&("01").equals(Flag)||Flag!=null&&("02").equals(Flag))){
            appntIncome=appntIncome.indexOf("-")>-1 ? appntIncome.substring(0,appntIncome.indexOf("-")):appntIncome;
            if(("5").equals(appntIncome)){//投保人年收入为5-10万
                return appntIncome;
            }else{
                String regEX="[^0-9]";
                Pattern p = Pattern.compile(regEX);
                Matcher m = p.matcher(appntIncome);
                appntIncome=m.replaceAll("");//将匹配到的matcher数字转化为String类型数字可用m.replaceAll("")
                if(!("").equals(appntIncome)&&appntIncome!=null&&Double.parseDouble(appntIncome)<=5){//投保人年收入为5万以下
                    appntIncome="0";
                }
            }
        }else if(!("").equals(Flag)&&Flag!=null&&("04").equals(Flag)){
            if(!("").equals(appntIncome)&&appntIncome!=null){
                double numberIncome=Double.parseDouble(appntIncome)/10000;
                appntIncome=Double.toString(numberIncome);
            }
        }else {
            if(!("").equals(appntIncome)&&appntIncome!=null){
                double numberIncome=Double.parseDouble(appntIncome)/10000;
                appntIncome=Double.toString(numberIncome);
            }
        }
        return appntIncome;
    }

    /**
     * 投保人家庭年收入处理
     * @return
     */
    public static String appntFamilyIncomeFormat(String familyMoney){
        double d;
        try {
            d = Double.parseDouble(familyMoney);
        }catch (NumberFormatException e){
            return familyMoney;
        }

        String wanYuan = String.valueOf(d/10000);

        if (wanYuan.contains("e") || wanYuan.contains("E")){
            BigDecimal bigDecimal = new BigDecimal(Double.parseDouble(wanYuan));
            wanYuan = bigDecimal.toString();
        }
        return wanYuan;
    }
    /**
     * 按给定的长度，输出字符串
     * @param srcStr 源串，使用“,”分隔不同串
     * @param lenStr 长度定义，使用“,”分隔不同串
     * @return 拼好的结果
     */
    public static String fixedLengthString(String srcStr, String lenStr) {
        if (srcStr == null || lenStr == null || srcStr.length() == 0
                || lenStr.length() == 0)
            return "";
        String[] srcArr = srcStr.split(",",-1);
        String[] lenArr = lenStr.split(",",-1);
        if (srcArr.length != lenArr.length) {
           // logger.error(""+srcArr.length+","+lenArr.length);
            return "长度非法";
        }
        StringBuffer resultBuffer = new StringBuffer();
        try {
            for (int i = 0; i < srcArr.length; i++) {
                int tLength = Integer.parseInt(lenArr[i]);
                resultBuffer.append(cutStringByByteLength(srcArr[i],tLength));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
        return resultBuffer.toString();
    }

    private static String cutStringByByteLength(String src, int length){

        int srcLength = src.length();
        int sumLength = 0;
        for (int i =0; i<srcLength; i ++){
            if(src.charAt(i)>255){
                sumLength+=2;
            }else{
                sumLength+=1;
            }
            if(sumLength==length)
                return src.substring(0,i+1);
            else if(sumLength-length==1){
                if(src.charAt(i-1)>255)
                    return src.substring(0,i)+" ";
                else{
                    return src.substring(0,i);
                }
            }
        }
        StringBuffer sb = new StringBuffer(src);
        for(int i = sumLength; i<length; i++){
            sb.append(' ');
        }
        return sb.toString();
    }
}
